extends Node2D
var player: CharacterBody2D
@export var bubble_scene: PackedScene
@export var spike_scene: PackedScene
@export var bee_scene: PackedScene
@export var bubble_spawn_distance: float = 300.0
@export var camera:Camera2D
signal bird_start
signal bird_stop
var has_bird_started=false
var bubble_timer: Timer
var spike_timer:Timer
var bee_timer:Timer
var has_bees_started=false
var initial_y=0
func _ready():
	player = $Player 
	bubble_timer = $BubbleTimer
	spike_timer = $SpikeTimer
	bee_timer =$BeeTimer
	initial_y=player.global_position.y
	
func _process(delta):
	var height_gained = (initial_y - player.global_position.y)/10
	if (height_gained)>1000 and not has_bees_started:
		has_bees_started=true
		bee_timer.start()
	elif(height_gained)< 1000 and has_bees_started:
		has_bees_started=false
		bee_timer.stop()
	if height_gained>2000 and not has_bird_started:
		has_bird_started=true
		bird_start.emit()
	elif height_gained<2000 and has_bird_started:
		has_bird_started=false
		bird_stop.emit()
		
func spawn_bubbles():
	var camera_width = camera.get_viewport().size.x
	var safe_distance = 100  # Minimum horizontal distance from the player

	for i in range(randi_range(1, 3)):
		var bubble_instance = bubble_scene.instantiate()
		var random_x_position = 0
		while abs(random_x_position) < safe_distance:
			random_x_position = randf_range(-camera_width / 2, camera_width / 2)
		bubble_spawn_distance = randf_range(-100, 200)
		bubble_instance.global_position = player.global_position + Vector2(random_x_position, -bubble_spawn_distance)
		add_child(bubble_instance)
func spawn_spike():
	var camera_width = camera.get_viewport().size.x
	var safe_distance = 100  # Minimum horizontal distance from the player

	for i in range(randi_range(1, 3)):
		var spike_instance = spike_scene.instantiate()
		var random_x_position = 0
		while abs(random_x_position) < safe_distance:
			random_x_position = randf_range(-camera_width / 2, camera_width / 2)
		spike_instance.global_position = player.global_position + Vector2(random_x_position, -900)
		add_child(spike_instance)
	
	
	
func spawn_bee():
	var camera_width = camera.get_viewport().size.x
	var safe_distance = 600  # Minimum horizontal distance from the player
	for i in range(randi_range(1, 2)):  # Spawn 1-2 bees
		var bee_instance = bee_scene.instantiate()
		var side=0
		if(randf()>0.5):
			side=-1
		else:
			side=1
		var x_position = player.global_position.x + (side * camera_width / 2)
		if abs(x_position - player.global_position.x) < safe_distance:
			x_position += side * safe_distance
		var y_position = player.global_position.y - randf_range(-200,200)
		
		bee_instance.global_position = Vector2(x_position, y_position)
		add_child(bee_instance)
func _on_bubble_timer_timeout():
	spawn_bubbles() 

func _on_spike_timer_timeout():
	spawn_spike()  

func _on_bee_timer_timeout():
	spawn_bee()
